package demo.service;

import cn.hutool.core.bean.BeanUtil;
import demo.Result;
import demo.dto.ResponseBonusDto;
import demo.entity.Bonus;
import demo.repository.BonusRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Bonus Service
 *
 * @author 肖溥博文
 * @version 1.5
 */
@Service
public class BonusService {
    @Autowired
    BonusRepository bonusRepository;

    /**
     * 增加 bonus
     *
     * @param userCompanyId 工作经历 id
     * @param amount        金额
     * @param type          种类
     * @param reason        理由
     * @return 结果对象，包含一个 bonus 对象
     */
    public Result addBonus(Long userCompanyId, Long amount, String type, String reason) {
        Bonus bonus = new Bonus();
        bonus.setUserCompanyId(userCompanyId);
        bonus.setAmount(amount);
        bonus.setType(type);
        bonus.setDate(new Date());
        bonus.setReason(reason);
        Bonus bonusSaved = bonusRepository.save(bonus);
        ResponseBonusDto responseBonusDto = new ResponseBonusDto();
        BeanUtil.copyProperties(bonusSaved, responseBonusDto);
        responseBonusDto.setBonusId(bonusSaved.getId());
        return Result.success("奖金/津贴添加成功", responseBonusDto);
    }

    /**
     * 按 bonus id 查找 bonus
     *
     * @param bonusId bonus id
     * @return bonus 对象，查找成功则包含一个 bonus 对象
     */
    public Result findByBonusId(Long bonusId) {
        Bonus bonus = bonusRepository.findBonusById(bonusId);
        return bonus == null ? Result.error("不存在该奖金/津贴记录") : Result.success("存在该奖金/津贴记录", bonus);
    }

    /**
     * 修改 bonus
     *
     * @param bonus  bonus 对象
     * @param amount 金额
     * @param reason 理由
     * @return 结果对象，包括一个 responseBonusDto 对象
     */
    public Result setBonus(Bonus bonus, Long amount, String reason) {
        bonus.setAmount(amount);
        bonus.setDate(new Date());
        bonus.setReason(reason);
        bonusRepository.save(bonus);
        ResponseBonusDto responseBonusDto = new ResponseBonusDto();
        BeanUtil.copyProperties(bonus, responseBonusDto);
        responseBonusDto.setBonusId(bonus.getId());
        return Result.success("奖金/津贴添加成功", responseBonusDto);
    }

    /**
     * 删除 bonus
     *
     * @param bonus bonus 对象
     * @return 结果对象
     */
    public Result deleteBonus(Bonus bonus) {
        bonusRepository.delete(bonus);
        return Result.success("奖金/津贴删除成功");
    }

    /**
     * 列出工作经历对应的所有 bonus
     *
     * @param userCompanyId 工作经历 id
     * @param type          bonus 种类
     * @return bonus 对象的数组
     */
    public Result listBonusesByUserCompanyId(Long userCompanyId, String type) {
        return Result.success("查找成功", bonusRepository.findBonusesByUserCompanyIdAndType(userCompanyId, type));
    }
}
